package com.mujin.keji.collectionsystem.utils;

import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.module.updata.dto.VisitUserDto;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 录音工具类
 *
 * @author weishixiong
 * @Time 2018-03-28
 */
public class RecorderUtil {
    private static final String TAG = "RecorderUtil";

    private MediaRecorder mRecorder = null;
    private long startTime;
    private long timeInterval;
    private boolean isRecording;
    private VisitUserDto visitUserDto;

    /**
     * 创建文件目录
     */
    private void createFileCatalogue() {
        File destDir = new File(Constant.Param.RECORDPATH);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }

    private String timeStamp = null;
    //录音文件夹
    private String recordDir = "aarecordings";
    //json文件
    private String jsonFileName = null;
    //录音文件
    private String recordFileName = null;

    public RecorderUtil(VisitUserDto visitUserDto, String timeStamp) {
        this.timeStamp = timeStamp;
        this.visitUserDto = visitUserDto;
        createFileCatalogue();
        recordFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + recordDir + "/" + timeStamp + ".m4a";
        jsonFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + recordDir + "/" + timeStamp + ".txt";
        this.visitUserDto.setFilePath(recordFileName);//设置文件地址
        this.visitUserDto.setTxtFilePath(jsonFileName);//设置文件地址
    }

    public VisitUserDto getVisitUserDto() {
        return visitUserDto;
    }

    public void setVisitUserDto(VisitUserDto visitUserDto) {
        this.visitUserDto = visitUserDto;
    }

    public String getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    public String getRecordDir() {
        return recordDir;
    }

    public void setRecordDir(String recordDir) {
        this.recordDir = recordDir;
    }

    public String getJsonFileName() {
        return jsonFileName;
    }

    public void setJsonFileName(String jsonFileName) {
        this.jsonFileName = jsonFileName;
    }

    public String getRecordFileName() {
        return recordFileName;
    }

    public void setRecordFileName(String recordFileName) {
        this.recordFileName = recordFileName;
    }

    /**
     * 开始录音
     */
    public void startRecording() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                if (recordFileName == null) return;
                if (isRecording) {
                    mRecorder.release();
                    mRecorder = null;
                }
                mRecorder = new MediaRecorder();
                //设置码率
                mRecorder.setAudioEncodingBitRate(75*1024);
                //// 设置音频源为麦克风
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                //// 设置录制的音频格式
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                //// 设置音频编码
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                //设置音频保存的文件
                mRecorder.setOutputFile(recordFileName);
                //设置所录制的声音的采样率
                mRecorder.setAudioSamplingRate(16000);

                startTime = System.currentTimeMillis();
                try {
                    mRecorder.prepare();
                    mRecorder.start();
                    isRecording = true;

                    String visitUserStr = JSONObject.toJSONString(visitUserDto);
                    //把字符写到文件
                    FileUtil.writeJsonToFile(jsonFileName, visitUserStr);


                } catch (Exception e) {
                    Log.e(TAG, "run: "+e );
                    //Logger.d(TAG, "prepare() failed");
                }

            }
        }.start();


    }

    /**
     * 停止录音
     */
    public void stopRecording() {
        if (recordFileName == null) return;
        timeInterval = System.currentTimeMillis() - startTime;
        try {
            if (timeInterval > 1000) {
                mRecorder.stop();
            }
            mRecorder.release();
            mRecorder = null;
            isRecording = false;
        } catch (Exception e) {
            //  Logger.d(TAG, "release() failed");
        }
    }

    /**
     * 取消语音
     */
    public synchronized void cancelRecording() {
        if (mRecorder != null) {
            try {
                mRecorder.release();
                mRecorder = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(recordFileName);
            file.deleteOnExit();
        }
        isRecording = false;
    }

    /**
     * 获取录音文件
     */
    public byte[] getDate() {
        if (recordFileName == null) return null;
        try {
            return readFile(new File(recordFileName));
        } catch (IOException e) {
            //Logger.d(TAG, "read file error" + e);
            return null;
        }
    }

    /**
     * 获取录音文件地址
     */
    public String getFilePath() {
        return recordFileName;
    }

    /**
     * 获取录音时长,单位秒
     */
    public long getTimeInterval() {
        return timeInterval / 1000;
    }

    /**
     * 将文件转化为byte[]
     *
     * @param file 输入文件
     */
    private static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}